<template>
  <div class="app-container">
    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button type="primary" plain icon="plus" @click="handleOpenDialog()">新增</el-button>
          <!-- <el-button
            type="danger"
            :disabled="selectIds.length === 0"
            icon="delete"
            @click="handleDelete()"
          >
            删除
          </el-button> -->
          <el-button icon="refresh" @click="handleQuery()">刷新</el-button>
        </div>
      </div>

      <el-table v-loading="loading" :data="deptList" row-key="id" default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" class="data-table__content"
        @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column prop="name" label="分类名称" min-width="200" />
        <el-table-column prop="code" label="分类编号" width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="系统内置" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.systemd" type="success">内置</el-tag>
            <el-tag v-else type="info">自定义</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="100" />

        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">
            <el-button type="primary" link size="small" icon="plus"
              @click.stop="handleOpenDialog(scope.row.id, undefined)">
              新增
            </el-button>
            <el-button type="primary" :disabled="scope.row.systemd" link size="small" icon="edit"
              @click.stop="handleOpenDialog(scope.row.parentId, scope.row.id)">
              编辑
            </el-button>
            <el-button type="danger" :disabled="scope.row.systemd" link size="small" icon="delete"
              @click.stop="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" @closed="handleCloseDialog">
      <el-form ref="deptFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="上级分类" prop="parentId">
          <el-tree-select v-model="formData.parentId" placeholder="选择上级分类" :data="deptOptions" filterable check-strictly
            :render-after-expand="false" />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类编号" prop="code">
          <el-input v-model="formData.code" placeholder="请输入分类编号" />
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number v-model="formData.sort" controls-position="right" style="width: 100px" :min="0" />
        </el-form-item>
        <el-form-item label="分类状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="true">正常</el-radio>
            <el-radio :value="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "MaterialCategory",
  inheritAttrs: false,
});

import MaterialCategoryAPI, {
  MaterialCategoryVO,
  MaterialCategoryForm,
  MaterialCategoryQuery,
} from "@/api/business/material/materialCategory.api";

const queryFormRef = ref();
const deptFormRef = ref();

const loading = ref(false);
const selectIds = ref<number[]>([]);
const queryParams = reactive<MaterialCategoryQuery>({});

const dialog = reactive({
  title: "",
  visible: false,
});

const deptList = ref<MaterialCategoryVO[]>();
const deptOptions = ref<OptionType[]>();
const formData = reactive<MaterialCategoryForm>({
  status: true,
  parentId: "0",
  sort: 1,
});

const rules = reactive({
  parentId: [{ required: true, message: "上级分类不能为空", trigger: "change" }],
  name: [{ required: true, message: "分类名称不能为空", trigger: "blur" }],
  code: [{ required: true, message: "分类编号不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
});

// 查询分类
function handleQuery() {
  loading.value = true;
  MaterialCategoryAPI.getList(queryParams).then((data) => {
    deptList.value = data;
    loading.value = false;
  });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开分类弹窗
 *
 * @param parentId 父分类ID
 * @param deptId 分类ID
 */
async function handleOpenDialog(parentId?: string, deptId?: string) {
  // 加载分类下拉数据
  const data = await MaterialCategoryAPI.getOptions();
  deptOptions.value = [
    {
      value: "0",
      label: "顶级分类",
      children: data,
    },
  ];

  dialog.visible = true;
  if (deptId) {
    dialog.title = "修改分类";
    MaterialCategoryAPI.getFormData(deptId).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增分类";
    formData.parentId = parentId || "0";
  }
}

// 提交分类表单
function handleSubmit() {
  deptFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const deptId = formData.id;
      if (deptId) {
        MaterialCategoryAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        MaterialCategoryAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 删除分类
function handleDelete(deptId?: string) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    MaterialCategoryAPI.deleteById(deptId || "0")
      .then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      })
      .finally(() => (loading.value = false));
  });
}

// 重置表单
function resetForm() {
  deptFormRef.value.resetFields();
  deptFormRef.value.clearValidate();

  formData.id = undefined;
  formData.parentId = "0";
  formData.status = true;
  formData.sort = 1;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>
